package com.bojiu.lawsearch.lawsearch.service.impl;

import com.bojiu.lawsearch.lawsearch.mapper.*;
import com.bojiu.lawsearch.lawsearch.model.*;
import com.bojiu.lawsearch.lawsearch.service.WechatUserService;
import com.bojiu.lawsearch.lawsearch.task.TaskInit;
import com.bojiu.lawsearch.lawsearch.util.*;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: afdiao
 * @Date：2020/3/1 21:26
 * @Description:
 */
@Service
@Slf4j
public class WechatUserServiceImpl implements WechatUserService {

    @Autowired
    WechatUserMapper wechatUserMapper;

//    @Autowired
//    StringRedisTemplate stringRedisTemplate;

    @Autowired
    EngineerMapper engineerMapper;

    @Autowired
    EngineerLabelMapper engineerLabelMapper;

    @Autowired
    UserCollectMapper userCollectMapper;

    @Autowired
    LawBaseInfoMapper lawBaseInfoMapper;

    @Autowired
    MsgUtil msgUtil;

    @Autowired
    UserAccountMapper userAccountMapper;

    @Autowired
    WxGoodsMapper wxGoodsMapper;

    @Autowired
    LabelMapper labelMapper;

    @Override
    public WechatUser exitUser(String unionid) {
        if (wechatUserMapper.selectCountByExample(UtilTools.createExampleByKey("unionid", unionid, WechatUser.class)) > 0) {
            //存在的话返回用户明细
            WechatUser wechatUser = (WechatUser) wechatUserMapper.selectOneByExample(UtilTools.createExampleByKey("unionid", unionid, WechatUser.class));
            return wechatUser;
        }
        return null;
    }

    @Override
    public JsonResult register(WechatUser wechatUser) {
        try {
            //判断手机号验证码是否正确
            if (!msgUtil.checkPhoneCode(wechatUser.getAccount(), wechatUser.getPhoneCode())) {
                return new JsonResult(ResultCode.ERRORCODE);
            }
            String unionid = wechatUser.getUnionid();
            //校验是否注册过
            if (wechatUserMapper.selectCountByExample(UtilTools.createExampleByKey("unionid", unionid, WechatUser.class)) > 0) {
                log.error("该人员已经注册");
                return new JsonResult(ResultCode.REGISTERED);
            }

            //校验手机号是否重复
            if (wechatUserMapper.selectCountByExample(UtilTools.createExampleByKey("account", wechatUser.getAccount(), WechatUser.class)) > 0) {
                log.error("该手机号已被使用");
                return new JsonResult(ResultCode.SAMEPHONE);
            }

            //判断微信信息是否过期
            if (!TaskInit.wechatInfo.containsKey(unionid)) {
                log.error("获取的微信信息已过期");
                return new JsonResult(ResultCode.TOKENOVERTIME);
            }
//            String redisKey = RedisUtil.getKeyBy3(RedisKey.PROJECT, RedisKey.WECHAT_USERINFO, unionid);
//            if (!stringRedisTemplate.hasKey(redisKey)) {
//                log.error("获取的微信信息已过期");
//                return new JsonResult(ResultCode.TOKENOVERTIME);
//            }

//            String userInfoStr = stringRedisTemplate.opsForValue().get(redisKey);
            String userInfoStr = TaskInit.wechatInfo.get(unionid);
            String info = new String(userInfoStr.getBytes("ISO-8859-1"), "UTF-8");
            JsonObject jsonObject = new Gson().fromJson(info, JsonObject.class);
            String nickname = jsonObject.get("nickname").getAsString();
            int sex = jsonObject.get("sex").getAsInt();
            String headimgurl = jsonObject.get("headimgurl").getAsString();
            String openid = jsonObject.get("openid").getAsString();

            //完善用户信息
            wechatUser.setNickName(nickname);
            wechatUser.setSex(sex);
            wechatUser.setHeadUrl(headimgurl);
            wechatUser.setOpenid(openid);

            //刚开始全部设置为普通人员
            wechatUser.setType(0);
            //入库
            wechatUserMapper.insertSelective(wechatUser);
            // 初始化账户余额
            // TODO: 2020/5/5 待验证
            UserAccount userAccount = new UserAccount();
            userAccount.setUser_id(wechatUser.getId());
            userAccount.setAccount(0);
            userAccount.setIntegral(0);
            userAccountMapper.insertSelective(userAccount);
            //获取userId
            int userId = wechatUserMapper.getMaxId();
            wechatUser.setId(userId);
            //注册成功后默认登录，刷新token
            String token = refreshLoginTime(userId);
            wechatUser.setSign(token);
            return new JsonResult(ResultCode.SUCCESS, wechatUser);
        } catch (Exception e) {
            log.error("error to register,error is :{}", e);
            return new JsonResult(ResultCode.FAIL);
        }
    }

    @Override
    public JsonResult gzRegister(WechatUser wechatUser) {
        JsonResult register = register(wechatUser);
        if (register.getCode().equals("200")) {
            String extendUioinId = wechatUser.getExtendUioinId();
            //更新关联上家id
            if (!"123".equals(extendUioinId)) {
                if (wechatUserMapper.selectCountByExample(UtilTools.createExampleByKey("unionid", extendUioinId, WechatUser.class)) > 0) {
                    WechatUser user = (WechatUser) wechatUserMapper.selectOneByExample(UtilTools.createExampleByKey("unionid", extendUioinId, WechatUser.class));
                    WechatUser upUser = new WechatUser();
                    upUser.setExtend(user.getId());
                    wechatUserMapper.updateByExampleSelective(upUser, UtilTools.createExampleByKey("unionid", wechatUser.getUnionid(), WechatUser.class));
                }
            }
            return new JsonResult(ResultCode.SUCCESS);
        } else {
            return register;
        }
    }

    @Override
    public JsonResult loginByPhone(String phone, String password) {
        try {
            int count = wechatUserMapper.selectCountByExample(UtilTools.createExampleByKey("account", phone, WechatUser.class));
            if (0 == count) {
                log.error("手机号不存在");
                return new JsonResult(ResultCode.ERRORPASSWORD);
            }
            WechatUser wechatUser = (WechatUser) wechatUserMapper.selectOneByExample(UtilTools.createExampleByKey("account", phone, WechatUser.class));
            if (!wechatUser.getPassword().equals(password)) {
                log.error("密码错误");
                return new JsonResult(ResultCode.ERRORPASSWORD);
            }

            //开始获取人员信息
            Integer userId = wechatUser.getId();
            String token = refreshLoginTime(userId);
            wechatUser.setSign(token);
            String memberTime = wechatUser.getMemberTime();
            if (StringUtils.isEmpty(memberTime)) {
                wechatUser.setMemberState(2);
            } else {
                Long time = Long.valueOf(wechatUser.getMemberTime());
                if (System.currentTimeMillis() / 1000 > time) {
                    //会员过期
                    wechatUser.setMemberState(3);
                } else {
                    wechatUser.setMemberState(1);
                    //显示什么会员
                    Integer goodsId = wechatUser.getGoodsId();
                    WxGoods wxGoods = (WxGoods) wxGoodsMapper.selectOneByExample(UtilTools.createExampleByKey("id", goodsId, WxGoods.class));
                    wechatUser.setMemberMessage(wxGoods.getMessage());
                }
            }
            return new JsonResult(ResultCode.SUCCESS, wechatUser);
        } catch (Exception e) {
            log.error("error to login by phone ,error is :{}", e);
            return new JsonResult(ResultCode.FAIL);
        }
    }

    /**
     * 刷新登陆时间
     *
     * @param userId 用户id
     * @return 返回加密token
     */
    @Override
    public String refreshLoginTime(int userId) throws Exception {
        long loginTime = System.currentTimeMillis() / 1000;
        WechatUser tokenKey = new WechatUser();
        tokenKey.setLoginTime(String.valueOf(loginTime));
        //更新登陆时间
        wechatUserMapper.updateByExampleSelective(tokenKey, UtilTools.createExampleByKey("id", userId, WechatUser.class));
        //加密
        JsonObject token = new JsonObject();
        token.addProperty("userId", userId);
        token.addProperty("loginTime", loginTime);
        String encrypt = EncryptUtil.encrypt(token.toString());
        return encrypt;
    }

    @Override
    public boolean checkToken(String account, String token) {
//        String tokenKey = RedisUtil.getKeyBy2(RedisKey.PROJECT, RedisKey.USERTOKEN);
//        if (!stringRedisTemplate.opsForHash().hasKey(token, account)) {
//            log.error("token no exist,account is :{}", account);
//            return false;
//        }
//        String oldToken = (String) stringRedisTemplate.opsForHash().get(tokenKey, account);
//        if (!oldToken.equals(token)) {
//            log.error("token 不一致,account is :{}  oletoken is :{}   token is :{}", account, oldToken, token);
//            return false;
//        }
        return true;
    }

    /**
     * 获取用户明细
     *
     * @param userId
     * @return
     */
    @Override
    public WechatUser getByUserId(int userId, String sign) {
        WechatUser wechatUser = (WechatUser) wechatUserMapper.selectOneByExample(UtilTools.createExampleByKey("id", userId, WechatUser.class));
        if (userAccountMapper.selectCountByExample(UtilTools.createExampleByKey("user_id", userId, UserAccount.class)) == 0) {
            UserAccount userAccount = new UserAccount();
            userAccount.setAccount(0);
            userAccount.setIntegral(0);
            wechatUser.setUserAccount(userAccount);
        } else {
            UserAccount userAccount = (UserAccount) userAccountMapper.selectOneByExample(UtilTools.createExampleByKey("user_id", userId, UserAccount.class));
            wechatUser.setUserAccount(userAccount);
        }
        wechatUser.setSign(sign);
        String memberTime = wechatUser.getMemberTime();
        if (StringUtils.isEmpty(memberTime)) {
            wechatUser.setMemberState(2);
        } else {
            Long time = Long.valueOf(wechatUser.getMemberTime());
            if (System.currentTimeMillis() / 1000 > time) {
                //会员过期
                wechatUser.setMemberState(3);
            } else {
                wechatUser.setMemberState(1);
                //显示什么会员
                Integer goodsId = wechatUser.getGoodsId();
                WxGoods wxGoods = (WxGoods) wxGoodsMapper.selectOneByExample(UtilTools.createExampleByKey("id", goodsId, WxGoods.class));
                wechatUser.setMemberMessage(wxGoods.getMessage());
            }
        }

        wechatUser.setIsApplyEngineer(2);
        //判断是否是工程师
        if (engineerMapper.selectCountByExample(UtilTools.createExampleByKey("user_id", userId, Engineer.class)) > 0) {
            wechatUser.setIsApplyEngineer(1);
            Engineer engineer = engineerMapper.getLastEngineer(userId);
            List<String> labelNames = labelMapper.getLabelNameInIds(UtilTools.changeStrForSql(engineer.getLabel_id()));
            engineer.setLabelNames(labelNames);
            wechatUser.setEngineer(engineer);
        }

        log.debug("member status is :{}", wechatUser.getMemberState());
        return wechatUser;
    }

    @Override
    public JsonResult updatePassword(String newPassword, String oldPassword, int userId) {
        WechatUser wechatUser = (WechatUser) wechatUserMapper.selectOneByExample(UtilTools.createExampleByKey("id", userId, WechatUser.class));
        if (oldPassword.equals(newPassword)) {
            log.error("新密码不能与原密码一致");
            return new JsonResult(ResultCode.SAMEPASSWORD);
        }
        if (!wechatUser.getPassword().equals(oldPassword)) {
            log.error("原密码不正确");
            return new JsonResult(ResultCode.ERRORPASSWORD);
        }
        WechatUser update = new WechatUser();
        update.setPassword(newPassword);
        wechatUserMapper.updateByExampleSelective(update, UtilTools.createExampleByKey("id", userId, WechatUser.class));
        return new JsonResult(ResultCode.SUCCESS);
    }

    @Override
    public void updateBaseInfo(String headImg, String nickName, int sex, String province, String city, int userId) {
        WechatUser wechatUser = new WechatUser();
        wechatUser.setHeadUrl(Constances.WEB_URL + headImg);
        wechatUser.setSex(sex);
        wechatUser.setNickName(nickName);
        wechatUser.setProvince(province);
        wechatUser.setCity(city);
        wechatUserMapper.updateByExampleSelective(wechatUser, UtilTools.createExampleByKey("id", userId, WechatUser.class));
    }

    @Transactional
    @Override
    public JsonResult registerEngineer(int userId, Engineer engineer) {
        //校验邮箱是否使用
        Map<String, Object> map = new HashMap<>();
        map.put("is_authentication", 1);
        map.put("mail", engineer.getMail());
        if (engineerMapper.selectCountByExample(UtilTools.createExampleByMap(map, Engineer.class)) > 0) {
            log.error("邮箱已被使用");
            return new JsonResult(ResultCode.SAMEMAIL);
        }

        map.clear();
        map.put("user_id", userId);
        map.put("is_authentication", 1);
        if (engineerMapper.selectCountByExample(UtilTools.createExampleByMap(map, Engineer.class)) > 0) {
            return new JsonResult(ResultCode.AUTHENTICATION_SUCCESS);
        }
        //还有待处理的申请则不给继续申请
        map.put("is_authentication", 0);
        if (engineerMapper.selectCountByExample(UtilTools.createExampleByMap(map, Engineer.class)) > 0) {
            return new JsonResult(ResultCode.SAME_DATA);
        }

        WechatUser wechatUser = (WechatUser) wechatUserMapper.selectOneByExample(UtilTools.createExampleByKey("id", userId, WechatUser.class));
        engineer.setUser_id(wechatUser.getId());
        engineer.setIs_authentication(0);
        engineerMapper.insertSelective(engineer);

        for (String id : engineer.getLabel_id().split(",")) {
            EngineerLabel engineerLabel = new EngineerLabel();
            engineerLabel.setUserId(engineer.getUser_id());
            engineerLabel.setLabelId(Integer.parseInt(id));
            engineerLabelMapper.insertSelective(engineerLabel);
        }
        return new JsonResult(ResultCode.SUCCESS);
    }

    @Override
    public JsonResult myCollect(int userId, String text) {
        List<Rule> myCollect = userCollectMapper.getMyCollect(userId, text);
        if (myCollect.isEmpty()) {
            return new JsonResult(ResultCode.SUCCESS);
        }

        Map<String, List<Rule>> result = new HashMap<>();
        for (Rule rule : myCollect) {
            Map<String, Object> map = new HashMap<>();
            map.put("user_id", userId);
            map.put("rules_id", rule.getId());
            UserCollect userCollect = (UserCollect) userCollectMapper.selectOneByExample(UtilTools.createExampleByMap(map, UserCollect.class));
            Integer labelId = userCollect.getLabelId();
            Label label = (Label) labelMapper.selectOneByExample(UtilTools.createExampleByKey("id", labelId, Label.class));
            String name = label.getName();

            if (result.containsKey(name)) {
                result.get(name).add(rule);
            } else {
                List<Rule> rules = new ArrayList<>();
                rules.add(rule);
                result.put(name, rules);
            }
        }
        List<Map<String, Object>> list = new ArrayList<>();
        for (String name : result.keySet()) {
            Map<String, Object> temp = new HashMap<>();
            temp.put("labelName", name);
            temp.put("rules", result.get(name));
            list.add(temp);
        }
//
//
//        Map<Integer, List<Rule>> map = new HashMap<>();
//        //开始分类
//        for (Rule rule : myCollect) {
//            Integer titleId = rule.getTitleId();
//            if (map.containsKey(titleId)) {
//                map.get(titleId).add(rule);
//            } else {
//                List<Rule> rules = new ArrayList<>();
//                rules.add(rule);
//                map.put(titleId, rules);
//            }
//        }
//        List<LawBaseInfo> lawBaseInfos = new ArrayList<>();
//        for (int titleId : map.keySet()) {
//            LawBaseInfo lawBaseInfo = (LawBaseInfo) lawBaseInfoMapper.selectOneByExample(UtilTools.createExampleByKey("id", titleId, LawBaseInfo.class));
//            lawBaseInfo.setRules(map.get(titleId));
//
//            lawBaseInfos.add(lawBaseInfo);
//        }
        return new JsonResult(ResultCode.SUCCESS, list);
    }
}
